package org.gitos.cloud.server.rpc;

import java.util.*;

import com.alibaba.fastjson.JSONObject;

import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.domain.device.Device;
import org.gitos.cloud.domain.device.Router;
import org.gitos.cloud.domain.mq.MqMsg;
import org.gitos.cloud.domain.rpc.LedRPC;
import org.gitos.cloud.domain.server.Rom;
import org.gitos.cloud.domain.tcp.Bucket;
import org.gitos.cloud.domain.tcp.DeviceId;
import org.gitos.cloud.server.mq.PushManager;
import org.gitos.cloud.server.service.RelationService;
import org.gitos.cloud.util.HexUtil;
import org.gitos.cloud.util.ZkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;


/**
 * Created by shizhengchu on 16/1/18.
 */
@Service
public class LedRPCImp extends CommonMethod implements LedRPC {

    private static Logger log = LoggerFactory.getLogger(LedRPCImp.class);
    @Autowired
    private PushManager pushManager;

    @Autowired
    private Router router;

    @Autowired
    private RelationService relationService;

    @Override
    public List<String> listActiveComet() {
        List<String> activeList = Collections.emptyList();
        try {
            activeList = ZkUtil.activeNode();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return activeList;
    }

    @Override
    public List<Device> listDevice() {
        return new ArrayList<Device>(router.allDevice());
    }

    @Override
    public Map<String, Object> dispatch(String deviceId, String order) {
        DeviceId did = null;
        JSONObject orderJo = null;
        try {
            did = DeviceId.instance(HexUtil.decodeHex(deviceId.toCharArray()));
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            return fail("设备ID错误");
        }
        try {
            orderJo = JSONObject.parseObject(order);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            return fail("指令错误");
        }
        Bucket bucket = new Bucket();
        bucket.setDeviceId(did);
        bucket.setCmd(orderJo.getShortValue("cmd"));
        bucket.setContent(orderJo.getString("content").getBytes());
        MqMsg msg = new MqMsg();
        msg.setBucket(bucket);
        Device device = router.fetchDevice(deviceId);
        if (device == null) {
            return fail(false);
        }
        msg.setChannelId(device.getChannelId());
        msg.setNodeId(device.getNodeId());
        pushManager.sendMsg(device.getNodeId(), msg);
        return success(true);
    }
}
